package com.nineclock.message.service.impl;

import cn.hutool.core.util.StrUtil;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.message.config.JPushManager;
import com.nineclock.message.dto.NcMessageDTO;
import com.nineclock.message.pojo.NcMessage;
import com.nineclock.message.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Autowired
    JPushManager jPushManager;

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void pushSingMessage(NcMessage message) throws Exception {
        //发送消息给管理员
        jPushManager.sendNotificationByAlias(message.getTitle(), message.getContent(), message.getTargets(), null);

        //存储倒mongodb
        mongoTemplate.save(message);
    }



    //获取推送历史记录返回客户端
    @Override
    public List<NcMessage> findMessageRecord(NcMessageDTO messageDTO) {
        Query query = new Query();
        if (messageDTO==null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        if (messageDTO.getId()!=null){
            query.addCriteria(Criteria.where("_id").is(messageDTO.getId()));
        }

        if (messageDTO.getType()!=null){
            query.addCriteria(Criteria.where("messageType").is(messageDTO.getType()));
        }

        if (messageDTO.getUserId()!=null){
            query.addCriteria(Criteria.where("applyUserId").is(messageDTO.getUserId()));
        }
        if (messageDTO.getTargetId()!=null){
            query.addCriteria(Criteria.where("approveUserId").is(messageDTO.getTargetId()));
        }
        query.with(Sort.by(Sort.Direction.ASC,"approveStatue"));


        //从MongoDB中获取
        List<NcMessage> messageList = mongoTemplate.find(query, NcMessage.class);

        return messageList;
    }

    //更新消息已读,切审核通过
    @Override
    public void updateMessageWithApproved(String messageId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(messageId));
        Update update = new Update();
            update.set("useStatus",1);
            update.set("approveStatue",1);
        mongoTemplate.updateFirst(query,update,NcMessage.class);
    }
}
